#!/usr/bin/env python
# -*- coding: utf-8 -*-

import subprocess
import time
import random
import logging
from datetime import datetime

# 设置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("binance_adb_trading.log"),
        logging.StreamHandler()
    ]
)

class BinanceADBBot:
    def __init__(self):
        # 币安应用上的关键位置坐标 (x, y)
        # 注意：这些坐标需要根据您的设备屏幕分辨率调整
        self.up_button = (540, 1600)     # 上涨按钮坐标
        self.down_button = (900, 1600)   # 下跌按钮坐标
        self.amount_input = (400, 1400)  # 金额输入框坐标
        self.confirm_button = (700, 1800) # 最终确认按钮坐标
        self.period_30m = (600, 1200)    # 30m周期选择按钮坐标
        
        self.amount = "5"                # 默认下注金额
        
        # 验证ADB连接
        self.check_adb_connection()

    def check_adb_connection(self):
        """检查ADB连接状态"""
        try:
            result = subprocess.run(['adb', 'devices'], capture_output=True, text=True)
            devices = result.stdout.strip().split('\n')[1:]
            
            if len(devices) == 0 or all('device' not in d for d in devices):
                logging.error("未检测到已连接的设备，请确保您的设备已连接并启用了USB调试")
                raise Exception("未检测到设备")
            
            logging.info(f"检测到设备: {devices}")
        except Exception as e:
            logging.error(f"ADB连接检查失败: {str(e)}")
            raise
    
    def tap(self, position, description):
        """点击屏幕上的指定位置"""
        try:
            x, y = position
            cmd = ['adb', 'shell', 'input', 'tap', str(x), str(y)]
            subprocess.run(cmd, check=True)
            logging.info(f"点击了{description}，坐标：{position}")
            return True
        except Exception as e:
            logging.error(f"点击{description}失败: {str(e)}")
            return False
    
    def input_text(self, text):
        """输入文本"""
        try:
            cmd = ['adb', 'shell', 'input', 'text', text]
            subprocess.run(cmd, check=True)
            logging.info(f"输入文本: {text}")
            return True
        except Exception as e:
            logging.error(f"输入文本失败: {str(e)}")
            return False
    
    def set_amount(self, amount=None):
        """设置下注金额"""
        if amount is None:
            amount = self.amount
            
        try:
            # 点击金额输入框
            self.tap(self.amount_input, "金额输入框")
            time.sleep(0.5)
            
            # 清除现有内容 (长按选择全部并删除)
            subprocess.run(['adb', 'shell', 'input', 'keyevent', 'KEYCODE_DPAD_RIGHT'], check=True)
            subprocess.run(['adb', 'shell', 'input', 'keyevent', 'KEYCODE_DEL'], check=True)
            
            # 输入新金额
            self.input_text(amount)
            time.sleep(0.5)
            
            logging.info(f"设置金额为: {amount}")
            return True
        except Exception as e:
            logging.error(f"设置金额失败: {str(e)}")
            return False

    def predict_trend(self):
        """
        根据策略决定是看涨还是看跌
        返回: 1 (看涨), -1 (看跌), 0 (不交易)
        """
        # 示例：时间策略 - 偶数分钟看涨，奇数分钟看跌
        current_minute = datetime.now().minute
        if current_minute % 2 == 0:
            return 1  # 看涨
        else:
            return -1  # 看跌

    def run(self, check_interval=10, trade_interval=300):
        """
        运行交易机器人
        check_interval: 检查间隔时间(秒)
        trade_interval: 交易间隔时间(秒)
        """
        last_trade_time = 0
        
        logging.info("币安ADB自动交易程序启动...")
        
        while True:
            try:
                current_time = time.time()
                
                # 检查是否应该交易
                if current_time - last_trade_time >= trade_interval:
                    direction = self.predict_trend()
                    
                    if direction != 0:
                        # 点击30m周期
                        self.tap(self.period_30m, "30m周期")
                        time.sleep(1)
                        
                        # 设置金额
                        self.set_amount()
                        time.sleep(1)
                        
                        # 执行交易 - 点击上涨或下跌按钮
                        if direction == 1:
                            success = self.tap(self.up_button, "上涨")
                        else:
                            success = self.tap(self.down_button, "下跌")
                        
                        time.sleep(1)
                        
                        # 点击最终确认按钮
                        if success:
                            self.tap(self.confirm_button, "确认按钮")
                            last_trade_time = current_time
                            logging.info(f"交易执行成功，方向: {'上涨' if direction == 1 else '下跌'}")
                            # 交易后休息一段时间
                            time.sleep(5)
                
                # 休息一段时间后再次检查
                logging.info(f"等待 {check_interval} 秒后进行下一次检查")
                time.sleep(check_interval)
                
            except KeyboardInterrupt:
                logging.info("程序被用户中断，正在退出...")
                break
            except Exception as e:
                logging.error(f"发生错误: {str(e)}")
                time.sleep(10)  # 出错后等待

if __name__ == "__main__":
    # 给用户一些时间准备
    print("程序将在5秒后开始运行，请确保已连接手机并启用了USB调试...")
    print("请确保币安APP已在手机上打开并处于前台")
    for i in range(5, 0, -1):
        print(f"{i}...")
        time.sleep(1)
    
    try:
        bot = BinanceADBBot()
        # 开始运行，每10秒检查一次，每5分钟最多交易一次
        bot.run(check_interval=10, trade_interval=300)
    except Exception as e:
        print(f"程序初始化失败: {str(e)}")
        print("请确保手机连接正常且已启用USB调试") 